package com.gjxx.netty;

import java.net.InetSocketAddress;

import com.alibaba.fastjson2.JSON;
import com.gjxx.buss.service.TerminalMsgProcessUpService;
import com.gjxx.common.constant.CacheConstants;
import com.gjxx.common.core.redis.RedisCache;
import com.gjxx.common.tcp.*;
import com.gjxx.mongo.service.CarDevOnlineStatusService;
import com.gjxx.netty.codec.TPMSConsts;
import com.gjxx.netty.session.Session;
import com.gjxx.netty.session.SessionManager;
import com.gjxx.netty.req.*;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * I/O数据读写处理类 TCP连接
 * <p>
 * tcp设备数据上传及下发数据
 *
 * @author lics
 * @version 1.0.0
 * @date 2023/6/1 13:12
 */
@ChannelHandler.Sharable
@Slf4j
@Component
public class TcpRequestHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private TerminalMsgProcessUpService terminalMsgProcessUpService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CarDevOnlineStatusService carDevOnlineStatusService;

    public static TcpRequestHandler tcpRequestHandler;

    private final SessionManager sessionManager = SessionManager.getInstance();

    private final MyDecoder decoder = new MyDecoder();

    @PostConstruct
    public void init() {
        tcpRequestHandler = this;
    }
        /**
         * 从客户端收到新的数据时，这个方法会在收到消息时被调用
         * @param ctx
         * @param msg
         */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            // 字节数据转换为针对于808消息结构的实体类
            PackageData pkg = (PackageData) msg;
            // 引用channel,以便回送数据给硬件
            pkg.setChannel(ctx.channel());
            tcpRequestHandler.processPackageData(pkg);
        }catch (Exception e){
            log.error("接收终端消息失败:" + e.getMessage());
        }
    }

    /**
     *
     * 处理业务逻辑
     *
     * @param packageData
     *
     */
    private void processPackageData(PackageData packageData) {
        final MsgHeader header = packageData.getMsgHeader();

        // 1. 终端心跳-消息体为空 ==> 平台通用应答
        if (TPMSConsts.msg_id_terminal_heart_beat == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.processTerminalHeartBeatMsg(packageData);
            } catch (Exception e) {
                log.error("[终端心跳]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //终端通用应答
        else if (TPMSConsts.msg_id_terminal_common_resp == header.getMsgId()) {
            try {
                TerminalCommonMsg msg = this.decoder.toTerminalCommonMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.processTerminalCommonMsg(msg);
            } catch (Exception e) {
                log.error("[终端通用应答]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        // 5. 终端鉴权 ==> 平台通用应答
        else if (TPMSConsts.msg_id_terminal_authentication == header.getMsgId()) {
            try {
                TerminalAuthenticationMsg authenticationMsg = new TerminalAuthenticationMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.processAuthMsg(authenticationMsg);
            } catch (Exception e) {
                log.error("[终端鉴权]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        // 6. 终端注册 ==> 终端注册应答
        else if (TPMSConsts.msg_id_terminal_register == header.getMsgId()) {
            try {
                TerminalRegisterMsg msg = this.decoder.toTerminalRegisterMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.processRegisterMsg(msg);
            } catch (Exception e) {
                log.error("[终端注册]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        // 7. 终端注销(终端注销数据消息体为空) ==> 平台通用应答
        else if (TPMSConsts.msg_id_terminal_log_out == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.processTerminalLogoutMsg(packageData);
            } catch (Exception e) {
                log.error("[终端注销]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        // 3. 位置信息汇报 ==> 平台通用应答
        else if (TPMSConsts.msg_id_terminal_location_info_upload == header.getMsgId()) {
            try {
                LocationInfoUploadMsg locationInfoUploadMsg = this.decoder.toLocationInfoUploadMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.processLocationInfoUploadMsg(locationInfoUploadMsg);
            } catch (Exception e) {
                log.error("[位置信息]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //位置信息查询应答
        else if (TPMSConsts.msg_id_location_query_resp == header.getMsgId()) {
            try {
                LocationInfoQueryMsg locationInfoQueryMsg = this.decoder.toLocationInfoQueryMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.locationInfoQueryMsg(locationInfoQueryMsg);
            } catch (Exception e) {
                log.error("[位置信息查询应答]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //摄像头立即拍摄命令应答
        else if (TPMSConsts.msg_id_photo_screen_resp == header.getMsgId()) {
            try {
                PhotoScreenMsg photoScreenMsg = this.decoder.toPhotoScreenMsg(packageData);
                tcpRequestHandler.terminalMsgProcessUpService.photoScreenMsg(photoScreenMsg);
            } catch (Exception e) {
                log.error("[摄像头立即拍摄命令应答]处理错误,phone={},flowid={},err={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //多媒体数据上传
        else if (TPMSConsts.msg_id_media_file_upload == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.mediaFileMsg(packageData);
            } catch (Exception e) {
                log.error("[多媒体数据上传]处理错误,phone={},flowid={},error={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //终端上传音视频资源列表
        else if (TPMSConsts.msg_id_terminal_video_list_resp == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.historyVideoMsg(packageData);
            } catch (Exception e) {
                log.error("[终端上传音视频资源列表]处理错误,phone={},flowid={},error={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //终端参数查询应答
        else if (TPMSConsts.msg_id_terminal_param_query_resp == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.paramQueryMsg(packageData);
            } catch (Exception e) {
                log.error("[终端参数查询应答]处理错误,phone={},flowid={},error={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        //终端上传音视频属性
        else if (TPMSConsts.msg_id_terminal_video_upload_attributes == header.getMsgId()) {
            try {
                tcpRequestHandler.terminalMsgProcessUpService.videoAttrUploadMsg(packageData);
            } catch (Exception e) {
                log.error("[终端上传音视频属性]处理错误,phone={},flowid={},error={}", header.getTerminalPhone(), header.getFlowId(),
                        e.getMessage());
                e.printStackTrace();
            }
        }
        else {// 其他情况
//            log.error(">[未知消息类型],phone={},msgId={},package={}", header.getTerminalPhone(), header.getMsgId(),
//                    packageData);
        }
    }

    /**
     * 客户端与服务端第一次建立连接时 执行
     *
     * @param ctx
     * @throws Exception
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        // 获取客户端 ip
        ctx.channel().read();
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        //此处不能使用ctx.close()，否则客户端始终无法与服务端建立连接 clientIp 客户端ip
        Session session = Session.buildSession(ctx.channel());
        sessionManager.put(session.getId(), session);
        log.info("与服务端第一次建立连接,连接IP:{}" ,clientIp );
    }


    /**
     * 从客户端收到新的数据、读取完成时调用
     *
     * @param ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
//        log.info("从客户端收到新的数据、读取完成时调用, channel Read Complete ");
        ctx.flush();
    }

    /**
     * 当出现 Throwable 对象才会被调用，即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        String sessionId = ctx.channel().id().asLongText();
        Session session = sessionManager.findBySessionId(sessionId);
        String phone = null;
        if(session != null){
            phone = session.getTerminalPhone();
        }
        log.error("netty连接异常:{},客户端手机号：{} ",cause.getMessage(),phone);
        if(phone != null && phone.length() > 0){
            tcpRequestHandler.redisCache.deleteObject(CacheConstants.CAR_DEV_ONLINE_STATUS + phone);
            tcpRequestHandler.carDevOnlineStatusService.delete(phone);
        }
        sessionManager.removeBySessionId(sessionId);
        cause.printStackTrace();
        ctx.close();//抛出异常，断开与客户端的连接
    }

    /**
     * 客户端与服务端 断连时 执行
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        String sessionId = ctx.channel().id().asLongText();
        Session session = sessionManager.findBySessionId(sessionId);
        String phone = null;
        if(session != null){
            phone = session.getTerminalPhone();
        }
        log.info("客户端与服务端断连,断连IP:{},客户端手机号：{}  " ,clientIp ,phone);
        if(phone != null && phone.length() > 0){
            tcpRequestHandler.redisCache.deleteObject(CacheConstants.CAR_DEV_ONLINE_STATUS + phone);
            tcpRequestHandler.carDevOnlineStatusService.delete(phone);
        }
        sessionManager.removeBySessionId(sessionId);
        ctx.close(); //断开连接时，必须关闭，否则造成资源浪费，并发量很大情况下可能造成宕机
    }

    /**
     * 当服务端read超时, 会调用这个方法
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        String sessionId = ctx.channel().id().asLongText();
        Session session = sessionManager.findBySessionId(sessionId);
        String phone = null;
        if(session != null){
            phone = session.getTerminalPhone();
        }
        log.info("服务端读取超时,断开连接,断连IP:{},客户端手机号：{} " ,clientIp ,phone);
        if(session.getTerminalPhone() != null && session.getTerminalPhone().length() > 0){
            tcpRequestHandler.redisCache.deleteObject(CacheConstants.CAR_DEV_ONLINE_STATUS + session.getTerminalPhone());
            tcpRequestHandler.carDevOnlineStatusService.delete(session.getTerminalPhone());
        }
        sessionManager.removeBySessionId(sessionId);
        ctx.close();//超时时断开连接
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
//        log.info("channelRegistered");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
//        log.info("channelUnregistered");
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) {
//        log.info("channelWritabilityChanged");
    }

}
